package com.xindaoapp.happypet.utils;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.bean.PostLandlordMessageInfo;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.ui.PostDetailImgsActivity;
import com.xindaoapp.happypet.ui.ProgressBarWebViewActivity;
import com.xindaoapp.happypet.ui.WebViewActivity;
import com.xindaoapp.happypet.utils.InputRegular.INPUTTYPE;
import com.xindaoapp.happypet.utils.InputRegular.InputTypeCall;
import com.xindaoapp.happypet.view.MxxBlurView;
import com.xindaoapp.happypet.view.MyTestVideoView;

public class PostContentManager {
    private final String ARTICLE = "article";
    private final String IMAGE = "image";
    private final String VIDEO = "video";
    /** 引用 */
    private final String QUOTE = "quote";
    /** 引用帖子 */
    private final String QUOTEPOST = "appquotethread";
    /** 引用视频 */
    private final String QUOTEVIDEO = "webvideo";

    private final Activity mContext;
    private final String mTid;

    public PostContentManager(Activity context, String mTid) {
        mContext = context;
        this.mTid = mTid;
    }

    /**
     * 组装帖子内容体
     * 
     * @param container
     * @param list
     */
    public void parsePostContainer(final LinearLayout container,
            final List<PostLandlordMessageInfo> list, final int position) {
        ArrayList<String> images = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            final PostLandlordMessageInfo info = list.get(i);
            if (info.type.equals(ARTICLE)) {// 文字
                container.addView(getPostArticle(info));
            } else if (info.type.equals(IMAGE) && info.width != 0 && !info.content.endsWith(".gif")) {// 图片
                try {
                    container.addView(getImageView(info, images, position));// &&
                } catch (Exception e) {
                }
                // !info.content.endsWith(".gif")
            } else if (info.type.equals(VIDEO)) {// 视频
                container.addView(getVideoView(info, position));
            } else if (info.type.equals(IMAGE) && info.content.endsWith(".gif")) {// gif
                try {
                    container.addView(getGifView(info));
                } catch (Exception e) {
                }
            } else if (info.type.equals(QUOTE)) {// 引用
                // container.addView(getQuoteView(info));
            } else if (info.type.equals(QUOTEVIDEO)) {// 引用视频
                container.addView(getQuoteVideoView(info));
            } else if (info.type.equals(QUOTEPOST)) {// 引用帖子
                container.addView(getQuotePostView(info));
            }
        }
    }

    private View getQuotePostView(final PostLandlordMessageInfo info) {
        final View view =
                LayoutInflater.from(mContext).inflate(R.layout.list_item_detail_quote_post, null);
        ((TextView) view.findViewById(R.id.name)).setText(info.appquotethreaddata.subject);
        if (!TextUtils.isEmpty(info.appquotethreaddata.urlthumb)) {
            ImageLoader.getInstance().displayImage(info.appquotethreaddata.urlthumb,
                    ((ImageView) view.findViewById(R.id.video_cover)));
        } else {
            view.findViewById(R.id.video_cover).setVisibility(View.GONE);
        }
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {// 跳转帖子详情
                Intent intent = new Intent(mContext, PostDetailActivity.class);
                intent.putExtra(Constants.KEY_POST_TID, info.appquotethreaddata.tid);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        });
        return view;
    }

    private View getQuoteVideoView(final PostLandlordMessageInfo info) {
        final View view =
                LayoutInflater.from(mContext).inflate(R.layout.list_item_detail_quote_video, null);
        ((TextView) view.findViewById(R.id.name)).setText(info.webvideodata.body);
        ImageLoader.getInstance().displayImage(info.webvideodata.coverpath,
                ((ImageView) view.findViewById(R.id.video_cover)));
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(Constants.KEY_TOP_BAR_TITLE, "视频");
                intent.putExtra(Constants.KEY_VIDEO_URL, info.webvideodata.url);
                mContext.startActivity(intent);
            }
        });
        return view;
    }

    /**
     * 楼主视频
     * 
     * @param info
     * @param position
     * @return
     */
    @SuppressLint("NewApi")
    private View getVideoView(final PostLandlordMessageInfo info, final int position) {
        final View view =
                LayoutInflater.from(mContext).inflate(R.layout.post_detail_play_vedio, null);
        mVideoHolder = new VideoHolder();
        mVideoHolder.imagePlay = view.findViewById(R.id.previre_play);
        mVideoHolder.imageCover = (ImageView) view.findViewById(R.id.preview_video);
        mVideoHolder.progressBar = view.findViewById(R.id.progress);
        if (!TextUtils.isEmpty(info.coverImg)) {
            ImageLoader.getInstance().displayImage(info.coverImg, mVideoHolder.imageCover);
        }

        mVideoHolder.myTestVideoView = (MyTestVideoView) view.findViewById(R.id.surfaceView);
        if (CommonParameter.sScreenWidth == 0 || CommonParameter.sScreenHeight == 0) {
            CommonParameter.sScreenWidth = MoccaPreferences.sScreenWidth.get();
            CommonParameter.sScreenHeight = MoccaPreferences.sScreenHeight.get();
        }

        try {
            mVideoHolder.myTestVideoView.setLayoutParams(new LinearLayout.LayoutParams(
                    CommonParameter.sScreenWidth, CommonParameter.sScreenWidth));
        } catch (Exception e) {
        }
        mVideoHolder.imageCover.setLayoutParams(new RelativeLayout.LayoutParams(
                CommonParameter.sScreenWidth, CommonParameter.sScreenWidth));

        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mVideoHolder.myTestVideoView.initVideoView();
                play(mVideoHolder, info, position);
            }
        });
        return view;
    }

    class VideoHolder {
        View imagePlay;
        ImageView imageCover;
        View progressBar;
        MyTestVideoView myTestVideoView;
    }

    private void play(final VideoHolder holder, PostLandlordMessageInfo info, final int position) {
        if (holder.myTestVideoView.isPreparing()) {
            return;
        }
        if (holder.imagePlay.getVisibility() == View.GONE) {
            holder.imagePlay.setVisibility(View.VISIBLE);
        } else {
            holder.imagePlay.setVisibility(View.GONE);
        }
        if (null == holder.progressBar.getTag()) {
            holder.progressBar.setTag("a");
            holder.progressBar.setVisibility(View.VISIBLE);
        }
        holder.imagePlay.setVisibility(View.GONE);
        if (holder.myTestVideoView.isNull() || !holder.myTestVideoView.isPlaying()) {
            holder.imagePlay.setVisibility(View.GONE);

            if (holder.myTestVideoView.isNull()) {
                holder.myTestVideoView.setVideoPath(info.content);
                holder.myTestVideoView.prepareAsync(new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {// 开始播放
                        holder.imageCover.setVisibility(View.GONE);
                        holder.progressBar.setVisibility(View.GONE);
                        holder.myTestVideoView.start();
                    }
                }, new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {// 播放完成
                        holder.imagePlay.setVisibility(View.VISIBLE);
                    }
                });
            } else {
                holder.myTestVideoView.start();
                holder.imagePlay.setVisibility(View.GONE);
            }
        } else {
            holder.myTestVideoView.pause();
            holder.imagePlay.setVisibility(View.VISIBLE);
        }
    }

    private VideoHolder mVideoHolder;

    public void pause(int position) {
        if (null != mVideoHolder && null != mVideoHolder.myTestVideoView) {
            mVideoHolder.imagePlay.setVisibility(View.VISIBLE);
            mVideoHolder.progressBar.setVisibility(View.GONE);
            mVideoHolder.myTestVideoView.pause();
        }
    }

    public void stopPlayback() {
        if (null != mVideoHolder && null != mVideoHolder.myTestVideoView) {
            mVideoHolder.myTestVideoView.stopPlayback();
        }
    }

    /**
     * 获取gif图片的view
     * 
     * @param info
     * @return
     */
    private View getGifView(PostLandlordMessageInfo info) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.show_gif, null);

        final WebView gifView = (WebView) layout.findViewById(R.id.showgif);

        // 这里在那时去掉,看效果
        // LayoutParams lp =
        // new LayoutParams(LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth
        // * info.height / info.width);
        // layout.setLayoutParams(lp);

        // gifView.setLayoutParams(lp);
        // // 设置可以支持缩放
        // gifView.getSettings().setSupportZoom(true);
        // // 设置出现缩放工具
        // gifView.getSettings().setBuiltInZoomControls(true);
        // // 扩大比例的缩放
        // gifView.getSettings().setUseWideViewPort(true);
        // // 自适应屏幕
        gifView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        gifView.getSettings().setLoadWithOverviewMode(true);

        int screenDensity = mContext.getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
        }
        gifView.getSettings().setDefaultZoom(zoomDensity);
        gifView.getSettings().setSupportZoom(false);


        gifView.loadDataWithBaseURL(null, "<center><img src=" + info.content + "></center>",
                "text/html", "utf-8", null);

        return layout;
    }

    /**
     * 引用
     * 
     * @param info
     * @return
     */
    private View getQuoteView(PostLandlordMessageInfo info) {
        View view = View.inflate(mContext, R.layout.item_post_yinyong, null);
        ((TextView) view.findViewById(R.id.name)).setText(CommonUtil.convetToHtml(
                CommonUtil.parseEmoji(String.format("“%s”", info.content)), mContext));
        return view;
    }

    /**
     * 获取帖子标题
     */
    public View getPostTitle(String content) {
        TextView tv = (TextView) View.inflate(mContext, R.layout.item_post_title, null);
        SpannableStringBuilder ssb =
                CommonUtil.convetToHtml(CommonUtil.parseEmoji(content), mContext);
        tv.setText(ssb);
        return tv;
    }

    /**
     * 文本（标题、内容）
     * 
     * @param info
     * @return
     */
    private View getPostArticle(PostLandlordMessageInfo info) {
        TextView tv = (TextView) View.inflate(mContext, R.layout.item_post_article, null);
        SpannableStringBuilder ssb =
                CommonUtil.convetToHtml(CommonUtil.parseEmoji(info.content), mContext);
        tv.setText(new InputRegular(mContext).parse(ssb,
                new IRequest<InputRegular.InputTypeCall>() {

                    @Override
                    public void request(InputTypeCall t) {
                        if (t.type == INPUTTYPE.AITE) {
                            Intent intent = new Intent(mContext, MainActivity.class);
                            intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                    UserInfoFragment.class.getCanonicalName());
                            Bundle bundle = new Bundle();
                            // bundle.putString(Constants.KEY_UID, friend.uid);
                            bundle.putString(Constants.KEY_USERNAME, t.name);
                            // bundle.putString(Constants.KEY_USERFACE, friend.userface);
                            intent.putExtra(Constants.KEY_BUNDLE, bundle);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        } else if (t.type == INPUTTYPE.URL) {
                            Intent intent = new Intent(mContext, ProgressBarWebViewActivity.class);
                            intent.putExtra(Constants.KEY_TOP_BAR_TITLE, "浏览器");
                            intent.putExtra(Constants.KEY_VIDEO_URL, t.name);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        }
                    }
                }));
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        return tv;
    }

    /**
     * 图片
     * 
     * @param info
     * @return
     */
    private View getImageView(final PostLandlordMessageInfo info, final ArrayList<String> images,
            int position) {
        View view = View.inflate(mContext, R.layout.item_post_image, null);
        final ImageView imageView = (ImageView) view.findViewById(R.id.icon);

        int width = info.width;
        int height = info.height;

        if (CommonParameter.sScreenWidth == 0) {
            CommonParameter.sScreenWidth = MoccaPreferences.sScreenWidth.get();
        }

        int maxWidth =
                CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, position == -1 ? 30 : 80);

        // if (info.width > maxWidth) {
        // width = maxWidth;
        // height = maxWidth * info.height / info.width;
        // }

        /** 替换上面的 */
        // float level = maxWidth * 3.0f / 4.0f;
        float level = maxWidth / 3.0f;
        if (info.width >= level) {
            width = maxWidth;
            height = maxWidth * info.height / info.width;
        }

        LayoutParams lp = new LayoutParams(width, height);
        imageView.setLayoutParams(lp);

        ImageSize minInageSize = new ImageSize(width, height);
        ImageLoader.getInstance().loadImage(info.content, minInageSize, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                imageView.setBackgroundResource(R.drawable.picture_loading);
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                imageView.setBackgroundResource(R.drawable.picture_loading);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                imageView.setImageBitmap(loadedImage);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });
        // ImageLoader.getInstance().displayImage(info.content, imageView);
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                MxxBlurView mxxB = new MxxBlurView(mContext);
                mxxB.drawBlurOnce();
                Intent intent = new Intent(mContext, PostDetailImgsActivity.class);
                // intent.putStringArrayListExtra(Constants.KEY_PHOTOS, images);
                intent.putExtra(Constants.PARAM_PHOTO_POSITION, info.aid);
                intent.putExtra(Constants.KEY_POST_TID, mTid);
                // 设置当前的偏移量
                // for (int i = 0; i < images.size(); i++) {
                // if (info.content.equals(images.get(i))) {
                // intent.putExtra(Constants.KEY_CURRENT_INDEX, i);
                // break;
                // }
                // }
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        });

        // ImageView imageView = new ImageView(mContext);
        // imageView.setScaleType(ScaleType.FIT_XY);
        // LayoutParams lp =
        // new LayoutParams(LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth
        // * info.height / info.width);
        // lp.topMargin = MARGINTOP;
        // imageView.setLayoutParams(lp);
        // if (CommonParameter.isLoadImg) {
        // ImageLoader.getInstance().displayImage(info.content, imageView);
        // } else {
        // imageView.setBackgroundResource(R.drawable.picture_loading);
        // }
        // images.add(info.content);
        // imageView.setOnClickListener(new OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // MxxBlurView mxxB = new MxxBlurView(mContext);
        // mxxB.drawBlurOnce();
        // Intent intent = new Intent(mContext, PostImageActivity.class);
        // intent.putStringArrayListExtra(Constants.KEY_PHOTOS, images);
        // // 设置当前的偏移量
        // for (int i = 0; i < images.size(); i++) {
        // if (info.content.equals(images.get(i))) {
        // intent.putExtra(Constants.KEY_CURRENT_INDEX, i);
        // break;
        // }
        // }
        // mContext.startActivity(intent);
        // }
        // });
        return view;
    }
}
